package com.cci.kangdao.wechatOrder.util.wxsdk;

import com.cci.kangdao.common.RedisKeys;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.PropertiesUtils;
import com.cci.kangdao.utilTool.LocalTimeUtil;
import com.cci.kangdao.utilTool.TokenUtils;
import com.cci.kangdao.wechatOrder.model.UserOutSideTokenT;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @description: 外部用户TOKEN生成工具类
 * @author: zyf
 * @create: 2021-03-24
 */
@Component
public class OutSideTokenUtils {

    @Autowired
    private RedisClientUtils redisClientUtils;
    @Autowired
    private PropertiesUtils propertiesUtils;

    private static final Integer cacheSeconds = 60*60;


    /**
     * 生成token
     * @param user
     * @param tokenT
     * @return
     */
    public UserOutSideTokenT cacheOutSideToken( UserT user, UserOutSideTokenT tokenT){

        Integer redisCacheTime = Integer.valueOf(propertiesUtils.getPropertiesValue("redisCacheTime"));
        //生成过期时间
        String userKey = RedisKeys.outSideToken(tokenT.getCompanyId(),tokenT.getSourceType(),tokenT.getOutSideID());
        if (user== null){
            user = new UserT();
        }
        //判断是否存在用户信息
        if (redisClientUtils.exists(userKey)){
            redisClientUtils.delkey(userKey);
        }
        if (tokenT.getToken()!=null && StringUtils.isBlank(tokenT.getToken()) && redisClientUtils.exists(tokenT.getToken())){
            redisClientUtils.delkey(RedisKeys.tokenKey(tokenT.getToken()));
        }
        //保存过期时间
        tokenT.setExpireTime(LocalTimeUtil.getRealExpireTime(redisCacheTime.longValue()));
        //保存用户信息
        redisClientUtils.setObject(userKey,user,redisCacheTime);
        //生成token
        String token = TokenUtils.getToken(userKey,redisCacheTime.longValue());
        tokenT.setToken(token);
        //缓存token
        redisClientUtils.setObject(RedisKeys.tokenKey(tokenT.getToken()),tokenT,redisCacheTime);
        //保存到缓存表
        return tokenT;
    }


}
